import axios from 'axios'
import store from '../store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { XXTEA } from '@/utils/xxtea.min'
import { getExpiresIn, getToken, reBuildRequestConfig, setExpiresIn, setToken } from '@/utils/auth'
import { message, Modal } from 'ant-design-vue'
export let isRelogin = { show: false }
export let isRefresh = false
import { removeToken } from '@/utils/auth'
import Vue from 'vue'
import { tansParams } from '@/utils/util'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 8000, // 请求超时时间
})
let keyarr = []

// 异常拦截处理器
const errorHandler = (error) => {
  console.log(error, '异常拦截处理器')
  if (error.response) {
    const data = error.response.data
    console.log('error.response', error.response)
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: '系统提示',
        description: data.message,
      })
    }
    if (error.response.status === 404) {
      notification.error({
        message: '系统提示',
        description: '很抱歉，资源未找到!',
      })
    }
    if (error.response.status === 504) {
      notification.error({
        message: '系统提示',
        description: '网络超时!',
      })
    }
    if (error.response.status === 4000) {
      if (token) {
        Modal.confirm({
          title: '系统提示',
          content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
          cancelButtonText: '取消',
          confirmButtonText: '重新登录',
          onOk() {
            store.dispatch('Logout').then(() => {
              // removeToken()
              try {
                let path = window.document.location.pathname
                console.log('location pathname -> ' + path)
                if (path != '/' && path.indexOf('/user/login') == -1) {
                  window.location.reload()
                }
              } catch (e) {
                window.location.reload()
              }
            })
          },
        })
      }
    }
    if (error.response.status === 4102) {
      if (token) {
        Modal.confirm({
          title: '系统提示',
          content: '未添加IP白名单，禁止登录，请联系系统管理员添加IP白名单！',
          cancelButtonText: '取消',
          confirmButtonText: '重新登录',
          onOk() {
            store.dispatch('Logout').then(() => {
              // removeToken()
              try {
                let path = window.document.location.pathname
                console.log('location pathname -> ' + path)
                if (path != '/' && path.indexOf('/user/login') == -1) {
                  window.location.reload()
                }
              } catch (e) {
                window.location.reload()
              }
            })
          },
        })
      }
    }
  }
  console.log(error, 'error')
  // return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use((config) => {
  const newConfig = JSON.parse(JSON.stringify(config))
  console.log('参数', newConfig)
  // const token = storage.get(ACCESS_TOKEN)
  // // 如果 token 存在
  // // 让每个请求携带自定义 token 请根据实际情况自行修改
  // if (token) {
  //   config.headers[ACCESS_TOKEN] = token
  // }

  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false

  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  if (isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime(),
    }
    const sessionObj = storage.get('sessionObj')
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      storage.set('sessionObj', requestObj)
    } else {
      const sUrl = sessionObj.url // 请求地址
      const sData = sessionObj.data // 请求数据
      const sTime = sessionObj.time // 请求时间
      const interval = 1000 // 间隔时间(ms)，小于此时间视为重复提交
      if (sData === requestObj.data && requestObj.time - sTime < interval && sUrl === requestObj.url) {
        const message = '数据正在处理，请勿重复提交'
        // console.warn(`[${sUrl}]: ` + message)
        return Promise.reject(new Error(message))
      } else {
        storage.set('sessionObj', requestObj)
      }
    }
  }
  const responseType = (config || {}).responseType

  keyarr.push(reBuildRequestConfig(config, responseType))

  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((res) => {
  let functionid = res.config.headers.functionid
  let keyvalue
  for (let i = 0; i < keyarr?.length; i++) {
    if (functionid == keyarr[i].key1) {
      keyvalue = keyarr[i].key2
      keyarr.splice(i, 1)
    }
  }
  const ss = XXTEA.decryptFromBase64(res.data, keyvalue)
  res = JSON.parse(ss)
  const code = res.code || 200
  // 获取错误信息
  const msg = res.msg
  if (code !== 200 && code !== 1) {
    message.error(msg);
    if (code === 4000) {
      if (!isRelogin.show) {
        isRelogin.show = true
        Modal.confirm({
          title: '系统提示',
          content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
          cancelButtonText: '取消',
          confirmButtonText: '重新登录',
          onOk() {
            store.dispatch('Logout').then(() => {
              // removeToken()
              try {
                let path = window.document.location.pathname
                console.log('location pathname -> ' + path)
                if (path != '/' && path.indexOf('/user/login') == -1) {
                  window.location.reload()
                }
              } catch (e) {
                window.location.reload()
              }
            })
          },
        })
      }
    }
  } else {
    isRelogin.show = false
  }
  console.log('接口返回结果', JSON.parse(JSON.stringify(res)))

  return res
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  },
}

export default request

export { installer as VueAxios, request as axios }
